<template>
  <div class="admin-dashboard">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <div>
          <h2>仪表板</h2>
          <p>银行管理系统总览</p>
        </div>
        <div class="header-actions">
          <el-button @click="handleRefresh" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-section">
      <el-col :span="6">
        <el-card class="stat-card users" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.totalUsers }}</div>
              <div class="stat-label">总用户数</div>
              <div class="stat-growth" :class="{ positive: stats.userGrowth >= 0 }">
                <el-icon v-if="stats.userGrowth >= 0"><ArrowUp /></el-icon>
                <el-icon v-else><ArrowDown /></el-icon>
                {{ Math.abs(stats.userGrowth) }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card cards" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><CreditCard /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.totalCards }}</div>
              <div class="stat-label">银行卡数</div>
              <div class="stat-growth" :class="{ positive: stats.cardGrowth >= 0 }">
                <el-icon v-if="stats.cardGrowth >= 0"><ArrowUp /></el-icon>
                <el-icon v-else><ArrowDown /></el-icon>
                {{ Math.abs(stats.cardGrowth) }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card trades" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.totalTrades }}</div>
              <div class="stat-label">今日交易</div>
              <div class="stat-growth" :class="{ positive: stats.tradeGrowth >= 0 }">
                <el-icon v-if="stats.tradeGrowth >= 0"><ArrowUp /></el-icon>
                <el-icon v-else><ArrowDown /></el-icon>
                {{ Math.abs(stats.tradeGrowth) }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card amount" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ stats.totalAmount.toLocaleString() }}</div>
              <div class="stat-label">交易总额</div>
              <div class="stat-growth" :class="{ positive: stats.amountGrowth >= 0 }">
                <el-icon v-if="stats.amountGrowth >= 0"><ArrowUp /></el-icon>
                <el-icon v-else><ArrowDown /></el-icon>
                {{ Math.abs(stats.amountGrowth) }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-section">
      <el-col :span="16">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>交易趋势</span>
              <el-radio-group v-model="trendPeriod" size="small" @change="updateTrendChart">
                <el-radio-button label="7">最近7天</el-radio-button>
                <el-radio-button label="30">最近30天</el-radio-button>
                <el-radio-button label="90">最近90天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container">
            <canvas ref="trendChart" width="600" height="300"></canvas>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <span>交易类型分布</span>
          </template>
          <div class="chart-container">
            <canvas ref="pieChart" width="300" height="300"></canvas>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近交易和系统状态 -->
    <el-row :gutter="20" class="bottom-section">
      <el-col :span="16">
        <el-card class="table-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>最近交易</span>
              <el-button type="text" @click="$router.push('/admin/trades')">查看全部</el-button>
            </div>
          </template>
          <el-table :data="recentTrades" v-loading="loading" stripe>
            <el-table-column prop="tradeid" label="交易ID" width="120" />
            <el-table-column prop="cardid" label="银行卡号" width="160">
              <template #default="{ row }">
                <span class="card-number">{{ formatCardNumber(row.cardid) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="tradetype" label="类型" width="80">
              <template #default="{ row }">
                <el-tag :type="getTradeTypeColor(row.tradetype)" size="small">
                  {{ row.tradetype }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="trademoney" label="金额" width="120">
              <template #default="{ row }">
                <span :class="getAmountClass(row.tradetype)">
                  ¥{{ Number(row.trademoney || 0).toLocaleString() }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="tradedate" label="时间" width="160">
              <template #default="{ row }">
                {{ formatDateTime(row.tradedate) }}
              </template>
            </el-table-column>
          </el-table>
          <div v-if="recentTrades.length === 0" class="empty-state">
            <el-empty description="暂无交易记录" />
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="status-card" shadow="hover">
          <template #header>
            <span>系统状态</span>
          </template>
          <div class="status-list">
            <div class="status-item">
              <div class="status-icon success">
                <el-icon><CircleCheckFilled /></el-icon>
              </div>
              <div class="status-info">
                <div class="status-title">系统运行正常</div>
                <div class="status-desc">所有服务正常运行</div>
              </div>
            </div>
            <div class="status-item">
              <div class="status-icon warning">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="status-info">
                <div class="status-title">数据库连接</div>
                <div class="status-desc">响应时间: {{ dbResponseTime }}ms</div>
              </div>
            </div>
            <div class="status-item">
              <div class="status-icon success">
                <el-icon><Connection /></el-icon>
              </div>
              <div class="status-info">
                <div class="status-title">API服务</div>
                <div class="status-desc">{{ apiStatus }}</div>
              </div>
            </div>
            <div class="status-item">
              <div class="status-icon info">
                <el-icon><Monitor /></el-icon>
              </div>
              <div class="status-info">
                <div class="status-title">在线用户</div>
                <div class="status-desc">{{ onlineUsers }} 人</div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 快捷操作 -->
        <el-card class="quick-actions-card" shadow="hover" style="margin-top: 20px;">
          <template #header>
            <span>快捷操作</span>
          </template>
          <div class="quick-actions">
            <el-button type="primary" @click="$router.push('/admin/customers')" block>
              <el-icon><User /></el-icon>
              客户管理
            </el-button>
            <el-button type="success" @click="$router.push('/admin/cards')" block>
              <el-icon><CreditCard /></el-icon>
              银行卡管理
            </el-button>
            <el-button type="warning" @click="$router.push('/admin/deposits')" block>
              <el-icon><Money /></el-icon>
              存款类型
            </el-button>
            <el-button type="info" @click="$router.push('/admin/trades')" block>
              <el-icon><TrendCharts /></el-icon>
              交易管理
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {
  User,
  CreditCard,
  TrendCharts,
  Money,
  Refresh,
  ArrowUp,
  ArrowDown,
  CircleCheckFilled,
  Clock,
  Connection,
  Monitor
} from '@element-plus/icons-vue'
import { adminCustomerApi } from '@/api/customer'
import { adminCardApi } from '@/api/card'
import { adminTradeApi } from '@/api/trade'

export default {
  name: 'AdminDashboard',
  components: {
    User,
    CreditCard,
    TrendCharts,
    Money,
    Refresh,
    ArrowUp,
    ArrowDown,
    CircleCheckFilled,
    Clock,
    Connection,
    Monitor
  },
  setup() {
    const loading = ref(false)
    const trendChart = ref(null)
    const pieChart = ref(null)
    const trendPeriod = ref('7')

    // 统计数据
    const stats = reactive({
      totalUsers: 0,
      totalCards: 0,
      totalTrades: 0,
      totalAmount: 0,
      userGrowth: 0,
      cardGrowth: 0,
      tradeGrowth: 0,
      amountGrowth: 0
    })

    // 最近交易
    const recentTrades = ref([])

    // 系统状态
    const dbResponseTime = ref(45)
    const apiStatus = ref('正常运行')
    const onlineUsers = ref(28)

    // 获取统计数据
    const fetchStats = async () => {
      loading.value = true
      try {
        // 获取用户统计
        const customerResponse = await adminCustomerApi.pageCustomer({
          current: 1,
          size: 1
        })
        if (customerResponse.code === 0) {
          stats.totalUsers = customerResponse.data?.total || 0
          stats.userGrowth = Math.floor(Math.random() * 20) - 5 // 模拟增长率
        }

        // 获取银行卡统计
        const cardResponse = await adminCardApi.pageCard({
          current: 1,
          size: 1
        })
        if (cardResponse.code === 0) {
          stats.totalCards = cardResponse.data?.total || 0
          stats.cardGrowth = Math.floor(Math.random() * 15) - 3 // 模拟增长率
        }

        // 获取今日交易统计
        const today = new Date().toISOString().split('T')[0]
        const tradeResponse = await adminTradeApi.pageTrade({
          current: 1,
          size: 100
        }, today, today)
        
        if (tradeResponse.code === 0) {
          const trades = tradeResponse.data?.records || []
          stats.totalTrades = trades.length
          stats.totalAmount = trades.reduce((sum, trade) => sum + Number(trade.trademoney || 0), 0)
          stats.tradeGrowth = Math.floor(Math.random() * 25) - 8 // 模拟增长率
          stats.amountGrowth = Math.floor(Math.random() * 30) - 10 // 模拟增长率
        }

      } catch (error) {
        console.error('获取统计数据失败:', error)
        ElMessage.error('获取统计数据失败')
      } finally {
        loading.value = false
      }
    }

    // 获取最近交易
    const fetchRecentTrades = async () => {
      try {
        const response = await adminTradeApi.pageTrade({
          current: 1,
          size: 5
        })
        
        if (response.code === 0) {
          recentTrades.value = response.data?.records || []
        }
      } catch (error) {
        console.error('获取最近交易失败:', error)
      }
    }

    // 绘制趋势图
    const drawTrendChart = () => {
      if (!trendChart.value) return

      const ctx = trendChart.value.getContext('2d')
      const canvas = trendChart.value
      const width = canvas.width
      const height = canvas.height

      // 清空画布
      ctx.clearRect(0, 0, width, height)

      // 模拟数据
      const days = parseInt(trendPeriod.value)
      const data = []
      for (let i = 0; i < days; i++) {
        data.push(Math.floor(Math.random() * 100) + 20)
      }

      // 绘制网格
      ctx.strokeStyle = '#e4e7ed'
      ctx.lineWidth = 1
      
      // 垂直网格线
      for (let i = 0; i <= 10; i++) {
        const x = (width / 10) * i
        ctx.beginPath()
        ctx.moveTo(x, 0)
        ctx.lineTo(x, height)
        ctx.stroke()
      }
      
      // 水平网格线
      for (let i = 0; i <= 6; i++) {
        const y = (height / 6) * i
        ctx.beginPath()
        ctx.moveTo(0, y)
        ctx.lineTo(width, y)
        ctx.stroke()
      }

      // 绘制数据线
      ctx.strokeStyle = '#409eff'
      ctx.lineWidth = 3
      ctx.beginPath()

      const stepX = width / (data.length - 1)
      const maxValue = Math.max(...data)
      
      data.forEach((value, index) => {
        const x = index * stepX
        const y = height - (value / maxValue) * height
        
        if (index === 0) {
          ctx.moveTo(x, y)
        } else {
          ctx.lineTo(x, y)
        }
      })
      
      ctx.stroke()

      // 绘制数据点
      ctx.fillStyle = '#409eff'
      data.forEach((value, index) => {
        const x = index * stepX
        const y = height - (value / maxValue) * height
        
        ctx.beginPath()
        ctx.arc(x, y, 4, 0, Math.PI * 2)
        ctx.fill()
      })
    }

    // 绘制饼图
    const drawPieChart = () => {
      if (!pieChart.value) return

      const ctx = pieChart.value.getContext('2d')
      const canvas = pieChart.value
      const centerX = canvas.width / 2
      const centerY = canvas.height / 2
      const radius = Math.min(centerX, centerY) - 20

      // 清空画布
      ctx.clearRect(0, 0, canvas.width, canvas.height)

      // 数据
      const data = [
        { label: '存款', value: 45, color: '#67c23a' },
        { label: '取款', value: 30, color: '#e6a23c' },
        { label: '转账', value: 25, color: '#409eff' }
      ]

      let currentAngle = -Math.PI / 2
      const total = data.reduce((sum, item) => sum + item.value, 0)

      // 绘制扇形
      data.forEach((item) => {
        const sliceAngle = (item.value / total) * 2 * Math.PI

        ctx.fillStyle = item.color
        ctx.beginPath()
        ctx.moveTo(centerX, centerY)
        ctx.arc(centerX, centerY, radius, currentAngle, currentAngle + sliceAngle)
        ctx.closePath()
        ctx.fill()

        // 绘制标签
        const labelAngle = currentAngle + sliceAngle / 2
        const labelX = centerX + Math.cos(labelAngle) * (radius * 0.7)
        const labelY = centerY + Math.sin(labelAngle) * (radius * 0.7)

        ctx.fillStyle = '#fff'
        ctx.font = '14px Arial'
        ctx.textAlign = 'center'
        ctx.fillText(`${item.label} ${item.value}%`, labelX, labelY)

        currentAngle += sliceAngle
      })
    }

    // 更新趋势图
    const updateTrendChart = () => {
      nextTick(() => {
        drawTrendChart()
      })
    }

    // 刷新数据
    const handleRefresh = () => {
      fetchStats()
      fetchRecentTrades()
      updateSystemStatus()
    }

    // 更新系统状态
    const updateSystemStatus = () => {
      dbResponseTime.value = Math.floor(Math.random() * 50) + 30
      onlineUsers.value = Math.floor(Math.random() * 50) + 10
    }

    // 工具函数
    const formatCardNumber = (cardNumber) => {
      if (!cardNumber) return ''
      return cardNumber.replace(/(\d{4})(?=\d)/g, '$1 ')
    }

    const formatDateTime = (dateTime) => {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString('zh-CN')
    }

    const getTradeTypeColor = (type) => {
      const colorMap = {
        '存款': 'success',
        '取款': 'warning',
        '转账': 'primary'
      }
      return colorMap[type] || 'info'
    }

    const getAmountClass = (type) => {
      const classMap = {
        '存款': 'amount-positive',
        '取款': 'amount-negative',
        '转账': 'amount-transfer'
      }
      return classMap[type] || ''
    }

    // 初始化
    onMounted(() => {
      fetchStats()
      fetchRecentTrades()
      updateSystemStatus()
      
      nextTick(() => {
        drawTrendChart()
        drawPieChart()
      })
    })

    return {
      loading,
      trendChart,
      pieChart,
      trendPeriod,
      stats,
      recentTrades,
      dbResponseTime,
      apiStatus,
      onlineUsers,
      handleRefresh,
      updateTrendChart,
      formatCardNumber,
      formatDateTime,
      getTradeTypeColor,
      getAmountClass
    }
  }
}
</script>

<style scoped>
.admin-dashboard {
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 28px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.stats-section {
  margin-bottom: 24px;
}

.stat-card {
  height: 120px;
  transition: all 0.3s ease;
  border: none;
  
  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  }
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 28px;
  color: white;
}

.stat-card.users .stat-icon {
  background: linear-gradient(135deg, #409eff, #66b1ff);
}

.stat-card.cards .stat-icon {
  background: linear-gradient(135deg, #67c23a, #85ce61);
}

.stat-card.trades .stat-icon {
  background: linear-gradient(135deg, #e6a23c, #ebb563);
}

.stat-card.amount .stat-icon {
  background: linear-gradient(135deg, #f56c6c, #f78989);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-growth {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #f56c6c;
  
  &.positive {
    color: #67c23a;
  }
  
  .el-icon {
    margin-right: 4px;
  }
}

.charts-section {
  margin-bottom: 24px;
}

.chart-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  padding: 20px;
  text-align: center;
}

.bottom-section {
  margin-bottom: 24px;
}

.table-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-number {
  font-family: 'Courier New', monospace;
  color: #409eff;
  font-weight: 500;
}

.amount-positive {
  color: #67c23a;
  font-weight: bold;
}

.amount-negative {
  color: #f56c6c;
  font-weight: bold;
}

.amount-transfer {
  color: #409eff;
  font-weight: bold;
}

.empty-state {
  padding: 40px;
  text-align: center;
}

.status-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.status-list {
  padding: 10px 0;
}

.status-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.status-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 18px;
  color: white;
  
  &.success {
    background: #67c23a;
  }
  
  &.warning {
    background: #e6a23c;
  }
  
  &.info {
    background: #409eff;
  }
}

.status-info {
  flex: 1;
}

.status-title {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
  margin-bottom: 4px;
}

.status-desc {
  font-size: 12px;
  color: #909399;
}

.quick-actions-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.quick-actions .el-button {
  justify-content: flex-start;
  padding: 12px 20px;
  
  .el-icon {
    margin-right: 8px;
  }
}

.el-card {
  border-radius: 12px;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}
</style> 